package com.zhs.gccs.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.location.Location;
import android.util.Log;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.zhs.gccs.event.EventLocation;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//https://blog.csdn.net/feinifi/article/details/120547127
@SuppressLint("MissingPermission")
public class GPSUtils {
    private static final String TAG = "GPSUtils";

    private static LocationClient mClient;
    private static MyLocationListener myLocationListener = new MyLocationListener();
    private static BDLocation mLocation = null;
    private static Activity mContext;

    public GPSUtils(Activity context) {

        context.runOnUiThread(() -> {
            this.mContext = context;

            // 定位初始化
            try {
                mClient = new LocationClient(context);
            } catch (Exception e) {
                e.printStackTrace();
            }
            LocationClientOption mOption = new LocationClientOption();
            mOption.setScanSpan(2000);
            mOption.setCoorType("gcj02");
            // mOption.setIsNeedAddress(true);
            mOption.setOpenGps(true);
            mClient.setLocOption(mOption);
            mClient.registerLocationListener(myLocationListener);
            mClient.start();
        });

    }

    /**
     * @return Location--->getLongitude()获取经度/getLatitude()获取纬度
     */
    public static BDLocation getLocation() {
        if (mLocation == null) {
            Log.e("GPSUtils", "setLocationData: 获取当前位置信息为空");
            return null;
        }
        return mLocation;
    }

    public static void removeUpdates() {
        if (null != mClient) {
            if (null != myLocationListener) {
                // 关闭前台定位服务
                mClient.disableLocInForeground(true);
                // 取消之前注册的 BDAbstractLocationListener 定位监听函数
                mClient.unRegisterLocationListener(myLocationListener);
                // 停止定位sdk
                mClient.stop();
            }
        }
    }

    static class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null) {
                return;
            }
            //角度
            // bdLocation.getDirection();
            mLocation = bdLocation;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = bdLocation.getTime() + "";
            Date date = null;
            try {
                date = format.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.print("Format To times:" + date.getTime());

            long myTime = date.getTime();

            Log.i(TAG, "时间：" + myTime + "");
            Log.e(TAG, "经度：" + bdLocation.getLongitude());
            Log.e(TAG, "纬度：" + bdLocation.getLatitude());
            Log.e(TAG, "======================================");
            Log.e(TAG, "=省：" + bdLocation.getProvince()+"  =");
            Log.e(TAG, "=市：" + bdLocation.getCity()+"      =");
            Log.e(TAG, "=县：" + bdLocation.getDistrict()+"  =");
            Log.e(TAG, "=镇：" + bdLocation.getTown()+"      =");
            Log.e(TAG, "======================================");
            mContext.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (null != bdLocation && !"4.9E-324".equals(bdLocation.getLongitude() + "")) {
                        double[] wgs84 = gcj02towgs84(bdLocation.getLongitude(), bdLocation.getLatitude());
                        // EventBus.getDefault().post(new LocationEvent(wgs84[0], wgs84[1], myTime,bdLocation.getProvince()+bdLocation.getCity()+bdLocation.getDistrict()+bdLocation.getTown()));
                        EventBus.getDefault().post(new EventLocation(wgs84[0], wgs84[1], myTime,bdLocation.getTown()+""));

                    }
                }
            });
        }
    }

    static double x_PI = 3.14159265358979324 * 3000.0 / 180.0;
    static double PI = 3.1415926535897932384626;
    static double a = 6378245.0;
    static double ee = 0.00669342162296594323;

    /**
     * GCJ02 转换为 WGS84
     *
     * @param lng
     * @param lat
     * @returns {*[]}
     */
    public static double[] gcj02towgs84(double lng, double lat) {
        if (out_of_china(lng, lat)) {
            double[] outDou = {lng, lat};
            return outDou;
        } else {
            double dlat = transformlat(lng - 105.0, lat - 35.0);
            double dlng = transformlng(lng - 105.0, lat - 35.0);
            double radlat = lat / 180.0 * PI;
            double magic = Math.sin(radlat);
            magic = 1 - ee * magic * magic;
            double sqrtmagic = Math.sqrt(magic);
            dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
            dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
            double mglat = lat + dlat;
            double mglng = lng + dlng;
            double[] inDou = {lng * 2 - mglng, lat * 2 - mglat};
            return inDou;
        }
    }





    /**
     * 判断是否在国内，不在国内则不做偏移
     *
     * @param lng
     * @param lat
     * @returns {boolean}
     */
    static boolean out_of_china(double lng, double lat) {
        return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271) || false);
    }

    static double transformlat(double lng, double lat) {
        double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    static double transformlng(double lng, double lat) {
        double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
        return ret;
    }

    //gps转照片的度分秒
    public static String gpsInfoConvert(double gpsInfo) {
        gpsInfo = Math.abs(gpsInfo);
        String dms = Location.convert(gpsInfo, Location.FORMAT_SECONDS);
        String[] splits = dms.split(":");
        String[] secnds = (splits[2]).split("\\.");
        String seconds;
        if (secnds.length == 0) {
            seconds = splits[2];
        } else {
            seconds = secnds[0];
        }
        return splits[0] + "/1," + splits[1] + "/1," + seconds + "/1";
    }

//    https://blog.csdn.net/androidwubo/article/details/76682716
    // 84->gcj02
//    public static Map<String, Double> transform(double lon, double lat) {
//        HashMap<String, Double> localHashMap = new HashMap<String, Double>();
//        if (outofChina(lat, lon)) {
//            localHashMap.put("lon", Double.valueOf(lon));
//            localHashMap.put("lat", Double.valueOf(lat));
//            return localHashMap;
//        }
//        double dLat = transformLat(lon - 105.0, lat - 35.0);
//        double dLon = transformLon(lon - 105.0, lat - 35.0);
//        double radLat = lat / 180.0 * pi;
//        double magic = Math.sin(radLat);
//        magic = 1 - ee * magic * magic;
//        double sqrtMagic = Math.sqrt(magic);
//        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
//        dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
//        double mgLat = lat + dLat;
//        double mgLon = lon + dLon;
//        localHashMap.put("lon", mgLon);
//        localHashMap.put("lat", mgLat);
//        return localHashMap;
//    }

    //照片的度分秒转gps
    public static Double convertToDegree(String stringDMS) {
        Float result = null;
        String[] DMS = stringDMS.split(",", 3);

        String[] stringD = DMS[0].split("/", 2);
        Double D0 = new Double(stringD[0]);
        Double D1 = new Double(stringD[1]);
        Double FloatD = DoubleOperation.div(D0, D1, 14);

        String[] stringM = DMS[1].split("/", 2);
        Double M0 = new Double(stringM[0]);
        Double M1 = new Double(stringM[1]);
        Double FloatM = DoubleOperation.div(M0, M1, 14);

        String[] stringS = DMS[2].split("/", 2);
        Double S0 = new Double(stringS[0]);
        Double S1 = new Double(stringS[1]);
        Double FloatS = DoubleOperation.div(S0, S1, 14);

        //result = new Float(FloatD + (FloatM/60) + (FloatS/3600));
        result = new Float(DoubleOperation.add(DoubleOperation.add(FloatD, DoubleOperation.div(FloatM, 60, 14)), DoubleOperation.div(FloatS, 3600, 14)));
        return (double) result;
    }


}
